package com.cgs.query.server.listener

import com.cgs.query.domain.Project2Define
import com.cgs.query.event.Project2DefineEvent
import com.cgs.query.service.IExecutionObjService
import com.cgs.query.service.IProject2DefineService
import com.cgs.query.util.Utils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.ApplicationListener
import org.springframework.scheduling.annotation.Async

/**
 * 解决版本的问题
 * 数据源的问题暂定
 */
open class Project2DefineListener : ApplicationListener<Project2DefineEvent> {

    @Autowired
    private lateinit var executionObjService: IExecutionObjService
    @Autowired
    private lateinit var project2DefineServiceImpl: IProject2DefineService

    @Async
    override fun onApplicationEvent(event: Project2DefineEvent?) {
        Utils.notNullAndThen(event) {
            val dealProject2DefineList = mutableListOf<Project2Define>()
            it.project2Defines.forEach { projectDefine ->
                Utils.notNullAndThen(executionObjService.findByDefineId(projectDefine.defineId).entries.firstOrNull()) { entry ->
                    projectDefine.version = entry.key
                    projectDefine.previewParams = entry.value.previewParams ?: ""
                    dealProject2DefineList.add(projectDefine)
                }
            }
            Utils.isNotEmptyAndThen(dealProject2DefineList) { project2DefineList ->
                project2DefineServiceImpl.save(project2DefineList)
            }
        }
    }
}